package com.briup.jd2407cms.web.Interceptor;

import com.briup.jd2407cms.exception.ServiceException;
import com.briup.jd2407cms.util.JwtUtil;
import com.briup.jd2407cms.util.result.ResultCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: JD2407-cms
 * @BelongsPackage: com.briup.jd2407cms.web.Interceptor
 * @Author: 鲨鲨天下第一
 * @CreateTime: 2024-11-19  20:02
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response, 
                             @NonNull Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1、读取url做个日志
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        log.info("当前拦截的请求为: {}",method + " " + url);
        // 2、放行预检请求
        if ("OPTIONS".equals(method)){
            return true;
        }

        // 从 HTTP请求头中取出 token
        String token = request.getHeader("Authorization");
        if (token == null){
            log.error("登录校验时，token不存在");
            throw new RuntimeException("无token，请重新登录");
        }

        // 验证token
        try {
            //解析JWT
            Claims claims = JwtUtil.parseJWT(token);
            String id = String.valueOf(claims.get("userId"));
            //专门为 /auth/user/info 提供服务
            request.setAttribute("userId",id);
        }catch (ExpiredJwtException e){
            //登录到期
            log.error("令牌已过期");
            throw new ServiceException(ResultCode.TOKEN_TIMEOUT);
        }catch (MalformedJwtException e){
            //令牌失效
            log.error("令牌解析失败, token无效!");
            throw new ServiceException(ResultCode.TOKEN_VALIDATE_ERROR);
        }catch (Exception e){
            log.error(e.getMessage());
            //服务器内部错误
            throw new ServiceException(ResultCode.SYSTEM_INNER_ERROR);
        }
        return true;
    }
}
